const Koa = require('koa');
const app = new Koa();
const Router = require('koa-router');
const router = new Router();
const { koaBody } = require('koa-body')
const token = 'jdlafjpafkpakpskdkajdada1200da'

app.use(koaBody({ multipart: true }))

// 设置跨域访问
app.use(async (ctx, next) => {
  // 设置允许跨域的域名，*代表允许任意域名跨域
  ctx.set('Access-Control-Allow-Origin', 'http://127.0.0.1:5500');
  ctx.set('Access-Control-Allow-Methods', '*');
  ctx.set('Access-Control-Allow-Credentials', true);
  ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');

  if (ctx.method === 'OPTIONS') {
    ctx.body = 200;
  } else {
    await next();
  }
})


// 登录接口
router.post('/login', (ctx) => {
  console.log('前端请求了登录接口');
  // 检验用户名和密码是否正确

  // 给前端设置登录凭证 cookie
  ctx.cookies.set('token', token, {
    maxAge: 1000 * 60 * 60 * 24,
    httpOnly: true, // 只能通过 HTTP 协议来读取 cookie，而不能通过 JavaScript 代码修改
  });

  // 向前端返回登录成功的状态码和消息

  ctx.body = {
    code: 200,
    msg: '登陆成功'
  }
  ctx.body = {
    code: 200,
    msg: '登陆成功'
  }
})

// 首页接口
router.get('/home', (ctx) => {
  // 获取前端传过来的token
  const token = ctx.cookies.get('token');
  // 验证 token是否有效
  console.log(token);

})



app.use(router.routes());
app.listen(3000, () => {
  console.log('server is running at port 3000');
});